<?php

$dns = "mysql:dbname=test1;host=127.0.0.1";
$username = "root";
$password = "root";

try {
    $pdo = new PDO($dns, $username, $password);
    echo "数据库连接成功...<br>";

    getComment($pdo);

    addUserToDB($pdo,"小二",18,"女");


} catch (PDOException $e) {
    echo "数据库连接出错: " + $e->getMessage();
}

/*
 * 获取评论用户信息
 */
function getComment($pdo)
{
    $sql = "SELECT c.`text`,c.`time`,s.`name`,s.`sex` FROM tb_comment c INNER JOIN tb_stu s ON c.`user_id` = s.`user_id`; ";
    $res = $pdo->query($sql);
    echo "<table border='1' width='800px'>";
    echo "<tr>";
    echo "<th>用户名</th>";
    echo "<th>性别</th>";
    echo "<th>评论</th>";
    echo "<th>时间</th>";
    echo "</tr>";
    foreach ($res as $row) {
        echo "<tr>";
        echo "<td align='center'>{$row["name"]}</td>";
        echo "<td align='center'>{$row["sex"]}</td>";
        echo "<td align='center'>{$row["text"]}</td>";
        echo "<td align='center'>{$row["time"]}</td>";
        echo "</tr>";
    }
    echo "</table>";
}

/*
 * 添加用户到数据库
 */
function addUserToDB($pdo,$name = null,$age = null,$sex = null){
    $sql = "INSERT into tb_user(name,age,sex) VALUES(?,?,?);";
    $stmt = $pdo->prepare($sql);
    $name = '小二';
    $age = 18;
    $sex = "女";
    $stmt->bindValue(1,$name);
    $stmt->bindValue(2,$age);
    $stmt->bindValue(3,$sex);
    $res = $stmt->execute();
    if($res>0)
        echo "<br>添加用户成功";
    else
        echo "<br>添加用户失败";
}